<?php

namespace App\Controllers;

class Collect extends Controller
{

    protected $url;  //要采集的url
    protected $savePath = '';  //保存路径
    static $content  = ''; //内容
    protected  $urls = [],$host,$http_type;
    public function __construct()
    {

    }


    public function handle($param = null)
    {


        $this->initParam($param);                              //初始化参数
        $this->initHost();                                      //初始化主机参数
        if(! $this->mkdir()); // return;                        //创建文件夹
        $this->initUrls();                                      //要采集的url
        $this->httpFileUrl();                                   //转换url
        $this->writeFile();                                    //写入文件
    }

    public function zip()
    {
        resolve('zip')->zipFolder($this->savePath);  //压缩文件
        $this->savePath = zipName($this->savePath);
        $this->uploadBos();
        $this->delZip();                                       //删除压缩包
    }


    public function uploadBos()
    {
        resolve('bos')->upload($this->savePath);  //上传文件到bos
    }


    public function initHost()
    {

        $host = parse_url($this->url);
        $this->host = $host['host'];
        $this->http_type = $host['scheme'];
    }


    public function initParam($param)
    {

        $this->url = $param[0];
        $class = get_class($this);
        $class =  lastName($class);
        $method = $class.'PathName';
        $this->savePath = storage_path().lcfirst($method)($this->url);
    }

    public function initUrls()
    {

    }

    //删除压缩包
    public function delZip()
    {
        unlink($this->savePath);
    }


    public function writeFile()
    {
        foreach ($this->urls as $index=>$url){
            if( $url == '')
                continue;
            $content = resolve('request')->getContent($url);
            file_put_contents($this->savePath.'/'.$index.'.png',$content);
        }
    }

    public function mkdir()
    {


        if(! is_dir($this->savePath)) {
            mkdir($this->savePath,0777,true);
            return true;
        }   return false;
    }


    //文件url
    public function httpFileUrl()
    {
        foreach ($this->urls as $k=>$url){
            $this->urls[$k] = $this->toUrl($url);
        }
    }

    public function toUrl($url)
    {
        if( strpos($url,"http") === 0)
            return $url;
        if ( strpos($url,'//'))
            return 'http:'.$url;

        if(substr($url,0,1) == '/')
            $url = substr($url,1);

            //    $url = substr($url,-1);
        return $this->http_type.'://'.$this->host.'/'.$url;
    }


}
